<template>
  <div>
    <div class="amap">
      <div>
        <el-form ref="form" label-position="left" :model="form">
          <el-row  :gutter="50">
            <el-col :span="12">
              <el-form-item label-width="90px" style="width:70%" label="企业名称">
                <el-select filterable  v-model="companyNo" >
                  <el-option
                    v-for="item in companyList"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label-width="90px" style="width:70%" label="上级路线">
                <el-select v-model="lineId" >
                  <el-option
                    v-for="item in lineList"
                    :key="item.originalId"
                    :label="item.name"
                    :value="item.originalId">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label-width="90px" class="jwd" label="企业简称">
                <el-input v-model="companyShortName"
              /></el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label-width="90px" class="jwd" label="排序号">
                <el-input v-model="sort"
              /></el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label-width="90px" class="jwd" label="经度">
                <el-input v-model="form.lng" /></el-form-item></el-col
            ><el-col :span="12">
              <el-form-item label-width="90px" class="jwd" label="纬度">
                <el-input v-model="form.lat" /></el-form-item
            ></el-col>
            <el-col :span="24">
              <el-form-item label-width="90px" style="width: 86%" label="地址">
                <el-select
                  v-model="keywords"
                  filterable
                  remote
                  reserve-keyword
                  placeholder="请输入关键词"
                  :remote-method="remoteMethod"
                  :loading="loading"
                  :clearable="true"
                  @change="currentSelect"
                >
                  <el-option
                    v-for="item in options"
                    :key="item.id"
                    :label="item.name"
                    :value="item"
                    class="one-text"
                  >
                    <span style="float: left">{{ item.name }}</span>
                    <span
                      style="float: right; color: #8492a6; font-size: 13px"
                      >{{ item.district }}</span
                    >
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>
      <div id="container" class="container"></div>
      <el-row style="text-align: center; margin-top: 20px">
        <el-col>
          <el-button
            v-loading="loading"
            class="dialogBtn"
            type="primary"
            @click="chongzhi"
            >重置</el-button
          >
          <el-button
            v-loading="loading"
            class="dialogBtn"
            type="primary"
            @click="submit"
            >保存</el-button
          >
        </el-col>
      </el-row>
    </div>
  </div>
</template>

<script>
import AMapLoader from '@amap/amap-jsapi-loader'
import { addPowerCustomerApi, editPowerCustomerApi, getCompanyListApi } from '@/api/fileFlow'

window._AMapSecurityConfig = {
  // 安全密钥

  // securityJsCode: '98404c23880b42f03d5faaa96a51a4f4'
  securityJsCode: '495b13f555dfc1483f5ab78c453e6315'
}
let AMap
export default {
  name: 'TestIndex',
  props: ['companyData', 'lineList', 'id'],
  data () {
    return {
      // 地图实例
      map: null,
      AMap: null,
      // 标记点
      marker: '',
      // 排序号
      sort: '',
      companyName: '',
      companyNo: '',
      lineId: '',
      companyShortName: '',
      // 地址逆解析
      geoCoder: null,
      // 搜索提示
      AutoComplete: null,
      // 搜索关键字
      keywords: '',
      // 位置信息
      form: {
        lng: '',
        lat: '',
        address: '',
        adcode: '' // 地区编码
      },
      // 搜索节流阀
      loading: false,
      // 搜索提示信息
      options: [],
      companyList: []
    }
  },
  created () {

  },
  watch: {
    companyNo: {
      handler (newVal, oldVal) {
        this.companyName = this.companyList.find(
          (item) => item.id === newVal
        )?.name
      },
      immediate: true
    }
  },
  async mounted () {
    await this.getCompanyList()
    if (this.companyData.id) {
      this.getInfoData()
    } else {
      this.lineId = this.id
    }
    this.initMap()
  },
  methods: {
    async getInfoData () {
      const data = this.companyData
      console.log(data)

      this.keywords = data.companyLocation
      this.powerPointName = data.powerPointName
      this.sort = data.sort
      this.companyNo = data.companyNo
      this.companyName = data.companyName
      this.lineId = data.lineId
      this.companyShortName = data.companyShortName
      this.form = {
        lng: data.companyLongitude,
        lat: data.companyLatitude,
        address: data.companyLocation
      }
    },
    async getCompanyList () {
      const res = await getCompanyListApi()
      console.log(res)
      this.companyList = res.data.list
    },
    initMap () {
      AMapLoader.load({
        // 你申请的Key
        // key: '36726b83d3822ae3f31648d75d5f64a2',
        key: '501062f563d27a055ca9c3debff4e31e',
        version: '2.0',
        // 需要用到的插件
        plugins: ['AMap.Geocoder', 'AMap.AutoComplete']
      })

        .then((_amap) => {
          AMap = _amap
          // console.log(AMap)
          this.map = new AMap.Map('container', {
            viewMode: '3D', // 是否为3D地图模式
            zoom: 5, // 初始化地图级别
            defaultCursor: 'grab',
            center: [105.602725, 37.076636] // 初始化地图中心点位置
          })
          // 地址逆解析插件
          this.geoCoder = new AMap.Geocoder({
            city: '010', // 城市设为北京，默认：“全国”
            radius: 1000 // 范围，默认：500
          })
          if (this.form.lng && this.form.lat) {
            this.setMapMarker()
          }
          // 搜索提示插件
          this.AutoComplete = new AMap.AutoComplete({ city: '全国' })
          // 点击获取经纬度;
          this.map.on('click', (e) => {
            // 获取经纬度
            this.form.lng = e.lnglat.lng
            this.form.lat = e.lnglat.lat
            // 清除点
            this.removeMarker()
            // 标记点
            this.setMapMarker()
          })
        })
        .catch(() => {})
    },

    // 标记点

    setMapMarker () {
      // 自动适应显示想显示的范围区域

      this.map?.setFitView()

      this.marker = new AMap.Marker({
        map: this.map,
        position: [this.form.lng, this.form.lat]
      })

      // 逆解析地址

      this.toGeoCoder()

      this.map?.setFitView()

      this.map.add(this.marker)
    },

    // 清除点

    removeMarker () {
      if (this.marker) {
        this.map.remove(this.marker)
      }
    },

    // 逆解析地址

    toGeoCoder () {
      const lnglat = [this.form.lng, this.form.lat]

      this.geoCoder.getAddress(lnglat, (status, result) => {
        // console.log(status)
        // console.log(result)
        if (status === 'complete' && result.regeocode) {
          this.form.address = result.regeocode.formattedAddress
        }
      })
    },

    // 搜索

    remoteMethod (query) {
      // console.log(query)
      if (query !== '') {
        this.loading = true
        setTimeout(() => {
          this.loading = false
          this.AutoComplete?.search(query, (status, result) => {
            this.options = result.tips?.filter((i) => i.location)
          })
        }, 200)
      } else {
        this.options = []
      }
    },

    // 选中提示

    currentSelect (val) {
      // 清空时不执行后面代码
      if (!val) {
        return
      }
      console.log(val)
      this.form = {
        lng: val.location?.lng,
        lat: val.location?.lat,
        address: val.district + val.address
        // adcode: val.adcode
      }
      this.keywords = val.name
      // 清除点
      this.removeMarker()
      // 标记点
      this.setMapMarker()
      console.log(this.form)
    },
    async submit () {
      this.loading = true
      try {
        const res = this.companyData.id
          ? await editPowerCustomerApi({
            id: this.companyData.id,
            companyName: this.companyName,
            companyNo: this.companyNo,
            companyLatitude: this.form.lat,
            companyLongitude: this.form.lng,
            companyLocation: this.keywords,
            sort: this.sort,
            lineId: this.lineId,
            companyShortName: this.companyShortName
          })
          : await addPowerCustomerApi({
            companyName: this.companyName,
            companyNo: this.companyNo,
            companyLatitude: this.form.lat,
            companyLongitude: this.form.lng,
            companyLocation: this.keywords,
            sort: this.sort,
            lineId: this.lineId,
            companyShortName: this.companyShortName
          })
        console.log(res)
        if (res.code == 200) {
          this.$message.success('保存成功')
          this.$emit('finish')
        } else {
          this.$message.error(res.message)
        }
      } catch (error) {
      } finally {
        this.loading = false
      }
    },
    chongzhi () {
      this.map.clearMap() // 清除地图上的覆盖物
      this.map.setZoomAndCenter(5, [105.602725, 37.076636]) // 设置地图缩放级别和中心点
    }
  },

  beforeDestroy () {
    // 在组件销毁前销毁地图实例
    if (this.map) {
      this.map.destroy()
    }
  }
}
</script>

<style lang="scss" scoped>
::v-deep.amap {
  width: 100%;
  .el-form-item {
    .el-form-item__content {
      width: 100% !important;
      .el-select {
        width: 100% !important;
      }
    }
  }
  .container {
    width: 100%;
    height: 400px;
  }
}

.el-select {
  width: 1000px;
}
::v-deep.jwd {
  .el-input {
     width: 70%;

  }
}
::v-deep.dizhi {
  .el-select {
    width: 400px !important;
    .el-input {
      width: 86%;
    }
  }
}
::v-deep .amap-logo {
  display: none !important;
  visibility: hidden !important;
}

::v-deep .amap-copyright {
  display: none !important;
  visibility: hidden !important;
}
</style>
